package dictcn.com.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import dictcn.com.R;
import dictcn.com.control.MyDatabaseHelper;
import dictcn.com.control.MytabOperate;
import dictcn.com.model.DBManager;
import dictcn.com.model.LocalLibrary;


@SuppressLint("SdCardPath")
public class MainInterface extends ActivityGroup{//主界面的activity类
	
    private ImageButton imgBtnPhoto;
    private AutoCompleteTextView editTextEdit;
    private ImageButton imgBtnSearch;
    private ImageButton imgBtnRefreash;
    private ImageButton imgBtnyj,imgBtnyt,imgbtnyl;
    private TextView txtZoumadengm;
    
    private SQLiteOpenHelper helper=null;
    private MytabOperate mytab=null;
    
    private SQLiteDatabase sqlite = null;
    private static final String DATABASENAME_FOR="dict.db";
    private static final String TABLE_LOCALLIBRARY ="locallibrary";
    
	private Drawable imgLeft;
	private Drawable imgRight;
	private Rect rBoundsLeft;
	private Rect rBoundsRight;
	private Drawable imgTitleRight;
	private Rect rTitleBounds;
	
	//语音请求标志
	private static final int VOICE_RECOGNITION_REQUEST_CODE =1001;
	
	//安装后本地数据库存放的位置
	private static final String PATH="/data/data/dictcn.com/databases/dict.db";
	
	private String temp[]=null;

    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);       
        
        //以下为软件第一次安装时把raw中的文件添加到本地文件中，主要是数据库
        SharedPreferences share=super.getSharedPreferences("first", MODE_PRIVATE);
		boolean first=share.getBoolean("first", true);
		if(first){
			SharedPreferences.Editor edit=share.edit();
			edit.putBoolean("first", false);
			edit.commit();			
			DBManager db=new DBManager(MainInterface.this);
			File to=new File(PATH);
			db.copyFile(to, true);
			Toast.makeText(MainInterface.this, "数据库文件加载完成！", Toast.LENGTH_LONG).show();			
		}	
		
		
        setupViewComponent();
    }
    
    //控件的初始化
	private void setupViewComponent(){
    	imgBtnPhoto=(ImageButton)findViewById(R.id.imgBtnPhoto);
    	editTextEdit=(AutoCompleteTextView)findViewById(R.id.editTextEdit);
    	imgBtnSearch=(ImageButton)findViewById(R.id.imgBtnSearch);
    	imgBtnRefreash=(ImageButton)findViewById(R.id.imgBtnRefreash);
    	imgBtnyj=(ImageButton)findViewById(R.id.imgBtnyj);
    	imgBtnyt=(ImageButton)findViewById(R.id.imgBtnyt);
    	imgbtnyl=(ImageButton)findViewById(R.id.imgBtnyl);
    	txtZoumadengm=(TextView)findViewById(R.id.txtZoumadeng);
    	
    	imgBtnPhoto.setOnClickListener(imgBtnPhotoOnClick);
    	imgBtnSearch.setOnClickListener(imgBtnSearchOnClick);
    	imgBtnRefreash.setOnClickListener(imgBtnRefreashOnClick);
    	imgBtnyj.setOnClickListener(imgBtnyjOnClick);
    	imgBtnyt.setOnClickListener(imgBtnytOnClick);
    	imgbtnyl.setOnClickListener(imgbtnylOnClick);
    	editTextEdit.setOnTouchListener(editTextEditOnTouch);
    	
    	//这两句设置Autocomplete张数据库的关联
    	sqlite = this.openOrCreateDatabase(DATABASENAME_FOR, 0, null);   
        MyCursorAdpter myCursorAdapter = new MyCursorAdpter(this, getCursor(), 1);
        
        
        editTextEdit.setAdapter(myCursorAdapter);
    	editTextEdit.setThreshold(1);
    	
    	Drawable draw[]=editTextEdit.getCompoundDrawables();
    	imgLeft=draw[0];
    	imgRight=draw[2];
    	
    	Drawable draw2[]=txtZoumadengm.getCompoundDrawables();
    	imgTitleRight=draw2[2];
    	rTitleBounds=imgTitleRight.getBounds();
    	  
    	//下方提示文本区域的监听
    	txtZoumadengm.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int x=(int)event.getX();
				int y=(int)event.getY();
				if(x>=v.getWidth()-rTitleBounds.width()-v.getPaddingRight()&&
							 x<=v.getWidth()&&
							 y>=v.getPaddingTop()&&
							 y<=v.getPaddingTop()+rTitleBounds.height()){					
					txtZoumadengm.setVisibility(View.INVISIBLE);
				}
				return false;
			}
		});
    	
    }

	//数据库游标获取记录
	public Cursor getCursor() {
    	
    	return sqlite.rawQuery("SELECT l_id AS _id ,letter_name,interpret FROM "+TABLE_LOCALLIBRARY, null);
    }
    
	
    private ImageButton.OnClickListener imgBtnPhotoOnClick=new ImageButton.OnClickListener(){

		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			//�˴�ʵ�������ѯ����
			
		}
    	
    };
    
    //查询按钮监听事件
    private ImageButton.OnClickListener imgBtnSearchOnClick=new ImageButton.OnClickListener(){

		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			
			//有网络访问的饿时候访问远程数据库连接
//			String word_name = "爱好";			
//			String result=cu.sayHello(word_name);	
//			Toast.makeText(MainInterface.this, result, Toast.LENGTH_LONG).show();
			
			
			
			//无网络访问的时候本地数据库连接
	        helper=new MyDatabaseHelper(MainInterface.this);
		    helper.getWritableDatabase();
			mytab=new MytabOperate(
			    	helper.getWritableDatabase());
			LocalLibrary local=mytab.findLocalLibrary(editTextEdit.getText().toString().trim());
			
			if(local.getL_id()==-1){
				Toast.makeText(MainInterface.this,"单词本地查找失败！",Toast.LENGTH_SHORT).show();
				editTextEdit.setText("");
			}
			else{	
				//查找单词成功，跳转显示界面
				Intent intent=new Intent();
				Bundle bundle=new Bundle();
				bundle.putSerializable("word", local);
				intent.putExtra("bundle", bundle);
				intent.setClass(MainInterface.this, ShowWordContent.class);
				startActivity(intent);	
			}
		}
    };
    
    
    private ImageButton.OnClickListener imgBtnRefreashOnClick=new ImageButton.OnClickListener(){

		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			//�˴�ʵ���ȴʸ��¹���
		}
    	
    };
    private ImageButton.OnClickListener imgBtnyjOnClick=new ImageButton.OnClickListener(){

		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			//�˴�ʵ��ÿ��һ�书��
		}
    	
    };
    private ImageButton.OnClickListener imgBtnytOnClick=new ImageButton.OnClickListener(){

		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			//�˴�ʵ��ÿ��һ����
		}
    	
    };
    private ImageButton.OnClickListener imgbtnylOnClick=new ImageButton.OnClickListener(){

		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			//�˴�ʵ��ÿ��һ������
		}	
		
    };
    
    
    //编辑框中的语音图片和历史记录图片触摸监听 
    private OnTouchListener editTextEditOnTouch=new OnTouchListener() {
		
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if(event.getAction()==MotionEvent.ACTION_UP && imgRight!=null && imgLeft!=null){
				
				//输入法的隐藏，方法1
				InputMethodManager imm = (InputMethodManager) getApplicationContext().
						getSystemService(Context.INPUT_METHOD_SERVICE); 
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				
				//输入法的隐藏，方法2
				/*((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).
    			hideSoftInputFromWindow(MainInterface.this.getCurrentFocus().getWindowToken(), 
    					InputMethodManager.HIDE_NOT_ALWAYS); //隐藏输入法	*/
				
				rBoundsLeft=imgRight.getBounds();
				rBoundsRight=imgRight.getBounds();
				final int x=(int)event.getX();
				final int y=(int)event.getY();
				 
			    if(x>=0&&x<=v.getPaddingLeft()+rBoundsLeft.width()&&
						 y>=v.getPaddingTop()&&
						 y<=v.getPaddingTop()+rBoundsLeft.height()){
					 
					 //implements the getVoiceResult here:
					 getVoice();

				 }
				 if(x>=v.getWidth()-rBoundsRight.width()-v.getPaddingRight()&&
						 x<=v.getWidth()&&
						 y>=v.getPaddingTop()&&
						 y<=v.getPaddingTop()+rBoundsRight.height()){
					
					 //implements the history record here:
					 
				 }
			 }
			return false;
		}
    };
    
    //语音控件的显示，注释已写过，详细情况见Translate.java中
    public void getVoice(){
    	if(isVoiceSoftInstall()){		
			Intent intent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
					RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
			intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Please say something!");
			startActivityForResult(intent,VOICE_RECOGNITION_REQUEST_CODE);
			
		}else{
			Dialog dlg=new AlertDialog.Builder(MainInterface.this)
			.setTitle("提示")
			.setIcon(R.drawable.icon)
			.setMessage("你没有安装语音插件，是否安装")
			.setNegativeButton("取消", null)
			.setPositiveButton("安装", new DialogInterface.OnClickListener() {				

				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Uri uri=Uri.parse("http://www.apk.anzhi.com/201107/19/com.google.android.voicesearch_32588500_0.apk");
					Intent intent=new Intent();
					intent.setAction(Intent.ACTION_VIEW);
					intent.setData(uri);
					startActivity(intent);			
				}
			})
			.create();
			dlg.show();	
		}
    }
    
    public boolean isVoiceSoftInstall(){

		//known if the listener activity is already for the system?
		PackageManager pm=getPackageManager();
		List<ResolveInfo> activities=pm.queryIntentActivities(
				new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if(activities.size()<=0)
			return false;
		else 
			return true;
	}
    
    //以下为后台数据查询显示，主要是autocomplete中数据的动态提示查询
    private class MyCursorAdpter extends CursorAdapter {
    	private int columnIndex;
    	
		public MyCursorAdpter(Context context, Cursor c, int col) {
			super(context, c);
			this.columnIndex = col;
		}

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            final LayoutInflater inflater = LayoutInflater.from(context);
            final TextView view = (TextView) inflater.inflate(
                    android.R.layout.simple_dropdown_item_1line, parent, false);
            return view;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {        	
            ((TextView) view).setText(cursor.getString(columnIndex));
        }
        
        @Override
        public String convertToString(Cursor cursor) {
        	Log.i("info", " convertToString ");
            return cursor.getString(columnIndex);
        }

        @Override
        public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
            if (constraint != null) {
            	String sql="SELECT l_id AS _id ,letter_name,interpret FROM "+TABLE_LOCALLIBRARY+" WHERE letter_name LIKE ?";
            	String[] selection = new String[]{"%"+ constraint.toString() +"%"};
                return sqlite.rawQuery(sql, selection);
            }
            else {
            	return null;
            }
        }
    }	
    
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		
		if(requestCode==VOICE_RECOGNITION_REQUEST_CODE && resultCode==RESULT_OK){
			ArrayList<String> result=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			int len=result.size();
			if(len>=5){
				temp=new String[]{result.get(0).toString(),result.get(1).toString(),result.get(2).toString(),
						result.get(3).toString(),result.get(4).toString()};
			}else{
				temp=new String[]{};
				for(int i=0;i<len;i++)
					temp[i]=result.get(i).toString();
			}
			try{
				if(len!=0&&temp!=null){
					Dialog dlg=new AlertDialog.Builder(MainInterface.this)
							.setTitle("语音 信息")
							.setIcon(R.drawable.icon)
							.setItems(temp, new OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									editTextEdit.setText(temp[which]);
								}
							})
							.setPositiveButton("取消", null)
							.create();
					dlg.show();	
				}
			}catch(Exception e){
				Toast.makeText(MainInterface.this,"语音无法识别", Toast.LENGTH_SHORT).show();
			}		
		}
			
		super.onActivityResult(requestCode, resultCode, data);
	}
    
    //数据库的关闭
    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	if(helper!=null){
    		helper.close();
    	}
    	if(sqlite!=null){
    		sqlite.close();
    	}
    	super.onDestroy();
    }
    
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode==KeyEvent.KEYCODE_BACK)
		{
			MainInterface.this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}
}